import { useEffect } from 'react'
import { useLocation } from 'react-router-dom'

/**
 * 性能监控组件
 * Story 3: Task 9 - 性能优化
 * 监控首屏加载时间和页面切换响应时间
 */
const PerformanceMonitor: React.FC = () => {
  const location = useLocation()

  // 监控首屏加载时间
  useEffect(() => {
    if ('PerformanceObserver' in window) {
      // First Contentful Paint
      const fcpObserver = new PerformanceObserver((list) => {
        for (const entry of list.getEntries()) {
          if (entry.name === 'first-contentful-paint') {
            console.log('✅ FCP:', entry.startTime.toFixed(2), 'ms')

            // 警告：FCP > 1800ms (移动端3秒目标的60%)
            if (entry.startTime > 1800) {
              console.warn('⚠️ Slow FCP detected:', entry.startTime.toFixed(2), 'ms')
            }
          }
        }
      })
      fcpObserver.observe({ entryTypes: ['paint'] })

      // Largest Contentful Paint
      const lcpObserver = new PerformanceObserver((list) => {
        const entries = list.getEntries()
        const lastEntry = entries[entries.length - 1]
        console.log('✅ LCP:', lastEntry.startTime.toFixed(2), 'ms')

        // 警告：LCP > 2500ms
        if (lastEntry.startTime > 2500) {
          console.warn('⚠️ Slow LCP detected:', lastEntry.startTime.toFixed(2), 'ms')
        }
      })
      lcpObserver.observe({ entryTypes: ['largest-contentful-paint'] })

      // First Input Delay
      const fidObserver = new PerformanceObserver((list) => {
        for (const entry of list.getEntries()) {
          const fid = (entry as any).processingStart - entry.startTime
          console.log('✅ FID:', fid.toFixed(2), 'ms')

          // 警告：FID > 100ms
          if (fid > 100) {
            console.warn('⚠️ Slow FID detected:', fid.toFixed(2), 'ms')
          }
        }
      })
      fidObserver.observe({ entryTypes: ['first-input'] })

      return () => {
        fcpObserver.disconnect()
        lcpObserver.disconnect()
        fidObserver.disconnect()
      }
    }
  }, [])

  // 监控页面切换时间
  useEffect(() => {
    const startTime = performance.now()

    // 使用 requestAnimationFrame 确保DOM更新完成后测量
    requestAnimationFrame(() => {
      const endTime = performance.now()
      const duration = endTime - startTime

      console.log(`📍 Navigation to ${location.pathname}:`, duration.toFixed(2), 'ms')

      // 警告：页面切换 > 100ms
      if (duration > 100) {
        console.warn(`⚠️ Slow navigation to ${location.pathname}:`, duration.toFixed(2), 'ms')
      }
    })
  }, [location.pathname])

  // 监控长任务
  useEffect(() => {
    if ('PerformanceObserver' in window) {
      const longTaskObserver = new PerformanceObserver((list) => {
        for (const entry of list.getEntries()) {
          console.warn('⚠️ Long Task detected:', {
            duration: entry.duration.toFixed(2) + 'ms',
            startTime: entry.startTime.toFixed(2) + 'ms'
          })
        }
      })

      try {
        longTaskObserver.observe({ entryTypes: ['longtask'] })
      } catch (e) {
        // longtask 可能不被支持
      }

      return () => longTaskObserver.disconnect()
    }
  }, [])

  // 监控内存使用（仅Chrome）
  useEffect(() => {
    const checkMemory = () => {
      if ('memory' in performance) {
        const memory = (performance as any).memory
        const usedMB = (memory.usedJSHeapSize / 1048576).toFixed(2)
        const limitMB = (memory.jsHeapSizeLimit / 1048576).toFixed(2)
        const percentage = ((memory.usedJSHeapSize / memory.jsHeapSizeLimit) * 100).toFixed(2)

        console.log(`💾 Memory: ${usedMB}MB / ${limitMB}MB (${percentage}%)`)

        // 警告：内存使用超过80%
        if (parseFloat(percentage) > 80) {
          console.warn('⚠️ High memory usage:', percentage + '%')
        }
      }
    }

    // 每30秒检查一次内存
    const interval = setInterval(checkMemory, 30000)

    return () => clearInterval(interval)
  }, [])

  return null
}

export default PerformanceMonitor
